use std::sync::Arc;
use anyhow::Result;
use sea_orm::DatabaseConnection;
use once_cell::sync::OnceCell;

use crate::config::Configs;
use crate::di::{ServiceContainer, services::*};
use crate::extension::index::index::index_spec_registry::IndexSpecRegistry;
use crate::extension::index::scheme_manager::SchemeManager;
use crate::services::{user_di::UserServiceDI, role_di::RoleServiceDI};

/// 全局应用容器实例
/// 
/// 使用OnceCell确保容器只初始化一次，并且线程安全
pub static APP_CONTAINER: OnceCell<Arc<ServiceContainer>> = OnceCell::new();

/// 应用容器管理器
/// 
/// 负责初始化和管理整个应用的依赖注入容器
pub struct AppContainer;

impl AppContainer {
    /// 初始化应用容器
    /// 
    /// 这个方法应该在应用启动时调用一次
    pub async fn initialize(db_connection: DatabaseConnection, config: Configs) -> Result<()> {
        let container = Arc::new(ServiceContainer::new());
        
        // 注册核心基础设施服务
        Self::register_infrastructure_services(&container, db_connection, config).await?;
        
        // 注册业务服务
        Self::register_business_services(&container).await?;
        
        // 设置全局容器
        APP_CONTAINER.set(container)
            .map_err(|_| anyhow::anyhow!("Failed to set global container"))?;
        
        Ok(())
    }

    /// 获取全局容器实例
    pub fn get_container() -> Result<Arc<ServiceContainer>> {
        APP_CONTAINER.get()
            .cloned()
            .ok_or_else(|| anyhow::anyhow!("Container not initialized"))
    }

    /// 解析服务实例
    pub fn resolve<T>() -> Result<Arc<T>>
    where
        T: 'static + Send + Sync,
    {
        let container = Self::get_container()?;
        container.resolve::<T>()
    }

    /// 注册基础设施服务
    async fn register_infrastructure_services(
        container: &ServiceContainer,
        db_connection: DatabaseConnection,
        config: Configs,
    ) -> Result<()> {
        // 注册数据库服务（单例）
        // 由于DatabaseConnection可能不实现Clone，我们直接使用Arc包装
        let db_connection = Arc::new(db_connection);
        container.register_singleton::<DatabaseService, _>({
            let db_conn = Arc::clone(&db_connection);
            move |_| {
                // 创建一个包装Arc<DatabaseConnection>的DatabaseService
                Ok(DatabaseService::new_with_arc(db_conn.clone()))
            }
        })?;

        // 注册配置服务（单例）
        container.register_singleton::<ConfigService, _>({
            let config = config.clone();
            move |_| Ok(ConfigService::new(config.clone()))
        })?;

        // 注册扩展存储服务（单例）
        container.register_singleton::<ExtensionStoreService, _>(|container| {
            let db_service = container.resolve::<DatabaseService>()?;
            Ok(ExtensionStoreService::new(db_service))
        })?;

        Ok(())
    }

    /// 注册业务服务
    async fn register_business_services(container: &ServiceContainer) -> Result<()> {
        // 注册角色服务（单例）
        container.register_singleton::<RoleServiceDI, _>(|container| {
            let store_service = container.resolve::<ExtensionStoreService>()?;
            Ok(RoleServiceDI::new(store_service))
        })?;

        // 注册用户服务（单例）
        container.register_singleton::<UserServiceDI, _>(|container| {
            let store_service = container.resolve::<ExtensionStoreService>()?;
            let role_service = container.resolve::<RoleServiceDI>()?;
            let config_service = container.resolve::<ConfigService>()?;
            Ok(UserServiceDI::new(store_service, role_service, config_service))
        })?;

        // 注册系统设置服务（单例）
        container.register_singleton::<SystemSettingService, _>(|container| {
            let store_service = container.resolve::<ExtensionStoreService>()?;
            Ok(SystemSettingService::new(store_service))
        })?;

        // 注册附件服务（单例）
        container.register_singleton::<AttachmentService, _>(|container| {
            let store_service = container.resolve::<ExtensionStoreService>()?;
            let config_service = container.resolve::<ConfigService>()?;
            Ok(AttachmentService::new(store_service, config_service))
        })?;

        // 注册 SchemeManager 服务（单例）
        container.register_singleton::<SchemeManager, _>(|_| {
            Ok(SchemeManager::new())
        })?;


        Ok(())
    }

    pub fn get_scheme_manager() -> Result<Arc<SchemeManager>> {
        Self::resolve::<SchemeManager>()
    }

    /// 获取用户服务实例
    pub fn get_user_service() -> Result<Arc<UserServiceDI>> {
        Self::resolve::<UserServiceDI>()
    }

    /// 获取角色服务实例
    pub fn get_role_service() -> Result<Arc<RoleServiceDI>> {
        Self::resolve::<RoleServiceDI>()
    }

    /// 获取配置服务实例
    pub fn get_config_service() -> Result<Arc<ConfigService>> {
        Self::resolve::<ConfigService>()
    }

    /// 获取数据库服务实例
    pub fn get_database_service() -> Result<Arc<DatabaseService>> {
        Self::resolve::<DatabaseService>()
    }

    /// 获取扩展存储服务实例
    pub fn get_store_service() -> Result<Arc<ExtensionStoreService>> {
        Self::resolve::<ExtensionStoreService>()
    }

    /// 清理容器（主要用于测试）
    #[cfg(test)]
    pub fn clear() {
        // 由于OnceCell不支持重置，这里只能清空单例缓存
        if let Some(container) = APP_CONTAINER.get() {
            let _ = container.clear_singletons();
        }
    }
}

/// 便捷宏，用于快速解析服务
#[macro_export]
macro_rules! resolve_service {
    ($service_type:ty) => {
        $crate::di::app_container::AppContainer::resolve::<$service_type>()
    };
}

#[macro_export]
macro_rules! get_scheme_manager {
    () => {
        $crate::di::app_container::AppContainer::get_scheme_manager()
    };
}

/// 便捷宏，用于获取特定服务
#[macro_export]
macro_rules! get_user_service {
    () => {
        $crate::di::app_container::AppContainer::get_user_service()
    };
}

#[macro_export]
macro_rules! get_role_service {
    () => {
        $crate::di::app_container::AppContainer::get_role_service()
    };
}

#[macro_export]
macro_rules! get_config_service {
    () => {
        $crate::di::app_container::AppContainer::get_config_service()
    };
}

#[macro_export]
macro_rules! get_database_service {
    () => {
        $crate::di::app_container::AppContainer::get_database_service()
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Server, DataBase, Log, Jwt, Cert};

    fn create_test_config() -> Configs {
        Configs {
            server: Server {
                name: "test".to_string(),
                address: "127.0.0.1:8080".to_string(),
                ssl: false,
            },
            database: DataBase {
                database_url: "sqlite::memory:".to_string(),
            },
            log: Log {
                filter_level: "info".to_string(),
                with_ansi: true,
                to_stdout: true,
                directory: "./logs".to_string(),
                file_name: "test.log".to_string(),
                rolling: "daily".to_string(),
            },
            jwt: Jwt {
                jwt_secret: "test_secret".to_string(),
                jwt_exp: 3600,
            },
            cert: Cert {
                cert: "test.pem".to_string(),
                key: "test.key".to_string(),
            },
        }
    }

    #[tokio::test]
    async fn test_container_initialization() {
        // 这个测试需要实际的数据库连接，暂时跳过
        // 在实际环境中，可以使用内存数据库进行测试
    }

    #[tokio::test]
    async fn test_service_resolution() {
        // 测试服务解析功能
        // 需要先初始化容器
    }

    #[tokio::test]
    async fn test_macro_usage() {
        // 测试便捷宏的使用
        // 需要先初始化容器
    }
}
